package com.chainyoung.component_tmperson.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chainyoung.common.appcommon.entity.EthPrice;
import com.chainyoung.common.appcommon.entity.HdWalletCache;
import com.chainyoung.common.appcommon.hdwallet.ExchangeCalculator;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.SystemUtils;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonFragmentComponent;
import com.chainyoung.component_tmperson.di.module.PersonFragmentModule;
import com.chainyoung.component_tmperson.entity.WalletPercent;
import com.chainyoung.component_tmperson.ui.activity.cloudwallet.SelectCoinTypeActivity;
import com.chainyoung.component_tmperson.ui.adapter.LocalWalletListAdapter;
import com.chainyoung.component_tmperson.ui.adapter.LocalWalletListAdapter1;
import com.chainyoung.component_tmperson.ui.mvp.contract.WalletLocalContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.WalletLocalPresenter;
import com.chainyoung.component_tmperson.ui.view.WalletPercentDetailView;
import com.chainyoung.component_tmperson.ui.view.WalletPercentView;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.chainyoung.common.appcommon.hdwallet.CoinConstant.ETH;
import static com.chainyoung.common.constant.LibConstant.WALLET_SAVE_TIME;
import static com.chainyoung.common.event.BaseEvent.EventCode.REFRESH_TOTAL_ASSET;
import static com.chainyoung.common.event.BaseEvent.EventCode.REFRESH_WALLET_BG;
import static com.chainyoung.component_tmperson.ui.fragment.MyPurseAddrListFragment.TYPE_LOCAl;

public class WalletLocalListFragment1 extends BaseFragment<WalletLocalPresenter> implements WalletLocalContract.View {


    @BindView(R2.id.total_amount)
    TextView tvAssetTotal;
    @BindView(R2.id.iv_add_wallet)
    ImageView ivAddWallet;
    @BindView(R2.id.view1)
    WalletPercentView walletPercentView;

    @BindView(R2.id.ll_percent)
    WalletPercentDetailView walletPercentDetailView;


    @BindView(R2.id.ll_top_content)
    RelativeLayout llTopContent;
    @BindView(R2.id.rv_list)
    RecyclerView rvList;

    @BindView(R2.id.ll_guide)
    RelativeLayout llGuide;
    @BindView(R2.id.fl_list)
    RelativeLayout flList;
    @BindView(R2.id.fl)
    FrameLayout fl;


    private boolean isLocalWalletOpened = false;
    private boolean isFistRequest = true;

    //private List<HdWallet> walletList = new ArrayList<>();//以后walletList 也只保证保留每一个币种的一个钱包

    private List<HdWalletCache> hdwallets = new ArrayList<>();

    private LocalWalletListAdapter1 adapter;


    private List<WalletPercent> walletPercentList = new ArrayList<>();
    private List<String> colors = new ArrayList<>();

    /**
     * 资产是否可见
     */
    private boolean isVisible = true;


    /**
     * 本地钱包总资产
     */
    private String totalAsset = "0";

    private BigDecimal ethRate = BigDecimal.valueOf(6.8409);//eth 对CNY 汇率


    public static WalletLocalListFragment1 newInstance(boolean isVisible) {
        WalletLocalListFragment1 fragment = new WalletLocalListFragment1();
        Bundle args = new Bundle();
        args.putBoolean("isVisible", isVisible);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            isVisible = getArguments().getBoolean("isVisible");
        }
    }


    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerPersonFragmentComponent.builder()
                .appComponent(appComponent)
                .personFragmentModule(new PersonFragmentModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void initUi() {
        super.initUi();
        //getWallets();
        //isLocalWalletOpened = WalletStoreManger.getHdWallets() != null;
        //  isLocalWalletOpened = SPUtil.getBoolean(LibConstant.isLocalWalletOpened);

        //llList.setVisibility(isLocalWalletOpened ? View.VISIBLE : View.GONE);
        //llGuide.setVisibility(isLocalWalletOpened ? View.GONE : View.VISIBLE);
//        if (isLocalWalletOpened) {
//            getWallets();
//        }
        //getWallets();
        initRecyclerView();
        setColors();

    }

    private void setColors() {
        colors.add("#ffffff");
        colors.add("#09C173");
        colors.add("#FFFFFF00");
    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.shape_divider_10));
        rvList.addItemDecoration(itemDecoration);
        //adapter = new LocalWalletListAdapter(walletList);
        long oldSavedtime = SPUtil.getLong(WALLET_SAVE_TIME);
        adapter = new LocalWalletListAdapter1(mContext, hdwallets, !(System.currentTimeMillis() - oldSavedtime >= 3 * 60 * 60 * 24 * 1000));
        rvList.setLayoutManager(layoutManager);
        rvList.setAdapter(adapter);

        setVisibleView();
    }


    @Override
    protected void initData() {


    }

    private void setVisibleView() {
        // tvAssetTotal.setText(isVisible ? "CNY " + totalAsset : "CNY ****");
        tvAssetTotal.setText("CNY " + totalAsset);
        //  adapter.setShowAsset(isVisible);
        // adapter.notifyDataSetChanged();
    }


    @Override
    protected void onFirstUserVisible() {
        /*if (!hdwallets.isEmpty()) {
            llList.setVisibility(View.VISIBLE);
            llGuide.setVisibility(View.GONE);
            getLocalWalletData(true);
        }*/
        initGoToTop();
        isFistRequest = true;
        getWallets();
        setVisibleView();


    }

    private void initGoToTop() {
        llTopContent.setFocusable(true);
        llTopContent.setFocusableInTouchMode(true);
        llTopContent.requestFocus();
    }

    @Override
    public void onUserVisible() {
        super.onUserVisible();
        initGoToTop();
        isFistRequest = false;
        getWallets();
        setVisibleView();
        /*if (!hdwallets.isEmpty()) {
            llList.setVisibility(View.VISIBLE);
            llGuide.setVisibility(View.GONE);
            getLocalWalletData(false);
        }*/
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_fragment_wallet_cloud_list1;
    }


    @OnClick(R2.id.tv_create_wallet)
    void createWallet() {
        Intent intent = new Intent(mContext, SelectCoinTypeActivity.class);
        intent.putExtra("walletType", TYPE_LOCAl);
        intent.putExtra("isCreatedWallet", true);
        mContext.startActivity(intent);
        // launch(SetPinCodeActivity.class);
    }


    @OnClick(R2.id.tv_import_wallet)
    void importWallet() {
        Intent intent = new Intent(mContext, SelectCoinTypeActivity.class);
        intent.putExtra("walletType", TYPE_LOCAl);
        intent.putExtra("isImportWallet", true);
        mContext.startActivity(intent);
        //launch(RestoreHdWalletActivity.class);
    }


    public void getWallets() {

        mPresenter.getAllHdWalletCaches(null);


    }


    @OnClick(R2.id.iv_add_wallet)
    void selectCoin() {
        Intent intent = new Intent(mContext, SelectCoinTypeActivity.class);
        intent.putExtra("walletType", TYPE_LOCAl);
        intent.putExtra("isAddWallet", true);//如果是本地钱包则按钮为导入钱包
        mContext.startActivity(intent);
    }

    private void saveWallets() {
        for (HdWalletCache wallet : hdwallets) {
            mPresenter.addHdWalletCache(wallet);
        }
    }


    public String getTotalAsset() {
        return totalAsset;
    }

    private void setTotoalLocalAsset() {
        BigDecimal totalLocal = BigDecimal.ZERO;
        for (HdWalletCache wallet : hdwallets) {
            BigDecimal bd = new BigDecimal(wallet.getBanlanceCny());
            totalLocal = totalLocal.add(bd);
        }
        totalAsset = String.valueOf(totalLocal.setScale(2, RoundingMode.DOWN));
        setVisibleView();
    }

    //----------------------------------------------缓存获取钱包--------------------------------------
    @Override
    public void onGetAllHdWalletCaches(List<HdWalletCache> datas) {
        ((WalletFragment1) getParentFragment()).finishRefresh();
        hdwallets.clear();
        if (datas != null) {
            hdwallets.addAll(datas);
        }
        if (!hdwallets.isEmpty()) {
            flList.setVisibility(View.VISIBLE);
            llGuide.setVisibility(View.GONE);
            fl.setBackgroundColor(ContextCompat.getColor(mContext, R.color._f2));
            EventBus.getDefault().post(new BaseEvent<>(REFRESH_WALLET_BG, false));

            setTotoalLocalAsset();

            //新增著钱包判断
            boolean isSetMainWalletAlready = false;
            for (HdWalletCache hdWallet : hdwallets) {
                if (hdWallet.isMainWallet()) {
                    isSetMainWalletAlready = true;
                }
            }
            if (!isSetMainWalletAlready) {
                hdwallets.get(0).setMainWallet(true);
            }


            getLocalWalletData(isFistRequest);
            adapter.notifyDataSetChanged();
        } else {
            flList.setVisibility(View.GONE);
            llGuide.setVisibility(View.VISIBLE);
            EventBus.getDefault().post(new BaseEvent<>(REFRESH_WALLET_BG, true));
            fl.setBackgroundColor(ContextCompat.getColor(mContext, R.color.transparent));
        }
    }

    @Override
    public void onAddHdWalletCacheSuccess(HdWalletCache data) {

    }


    //----------------------------------------------请求以太坊获取钱包数据----------------------------
    private void getLocalWalletData(boolean isFirst) {

        if (!hdwallets.isEmpty()) {
            for (HdWalletCache wallet : hdwallets) {
                if (wallet.getCoinType().equals(ETH)) {
                    mPresenter.getSingleEthBalance(wallet.getAddress(), isFirst);
                }
            }
        }

    }

    private void getUsdCnyRate() {
        mPresenter.getUsdCnyRate("usd", "cny");
    }

    private void getEthPrice() {
        mPresenter.getEthPrice();
    }


    @Override
    public void onGetSingleEthBalanceSuccess(String data, String addr) {
        // refreshLayout.finishRefresh();
        for (HdWalletCache wallet : hdwallets) {
            if (wallet.getCoinType().equals(ETH) && wallet.getAddress().equals(addr)) {
                //此处以后余额 转账存数据库 进行单位换算 原本返回wei 换算成ether
                if (new BigDecimal(data).compareTo(BigDecimal.ZERO) == 0) {
                    wallet.setBalance("0");
                } else {
                    wallet.setBalance(new BigDecimal(data).divide(ExchangeCalculator.ONE_ETHER, 8, RoundingMode.DOWN) + "");
                }
            }
        }
        //saveWallets();
        adapter.notifyDataSetChanged();
        getUsdCnyRate();

    }

    @Override
    public void onGetSingleEthBalanceFailed() {
        //refreshLayout.finishRefresh();
    }

    @Override
    public void onGetUsdCnyRateSuccessed(String data) {
        ethRate = new BigDecimal(data);
        getEthPrice();
    }

    @Override
    public void onGetEthPriceSuccessed(String data) {
        EthPrice ethPrice = new Gson().fromJson(data, EthPrice.class);
        BigDecimal ethCny = new BigDecimal(ethPrice.getEthusd()).multiply(ethRate);
        BigDecimal totalLocal = BigDecimal.ZERO;

        for (HdWalletCache wallet : hdwallets) {
            if (wallet.getCoinType().equals(ETH)) {
                BigDecimal bd = new BigDecimal(wallet.getBalance()).multiply(ethCny);
                wallet.setBanlanceCny(bd.setScale(2, RoundingMode.DOWN) + "");
                totalLocal = totalLocal.add(bd);
            }
        }
        saveWallets();
        adapter.notifyDataSetChanged();
        //设置总额
        totalAsset = String.valueOf(totalLocal.setScale(2, RoundingMode.DOWN));
        // setVisibleView();

        updatePercentView();
        EventBus.getDefault().post(new BaseEvent<>(REFRESH_TOTAL_ASSET));

    }

    private void updatePercentView() {
        if (hdwallets.isEmpty()) {

        } else {
            walletPercentList.clear();
            switch (hdwallets.size()) {
                case 1:
                case 2:
                    for (int i = 0; i < hdwallets.size(); i++) {
                        if (new BigDecimal(getTotalAsset()).compareTo(BigDecimal.ZERO) > 0) {
                            if (Double.valueOf(hdwallets.get(i).getBanlanceCny()).compareTo(0d) > 0) {
                                walletPercentList.add(new WalletPercent(hdwallets.get(i).getWalletName(), colors.get(i),
                                        Double.valueOf(hdwallets.get(i).getBanlanceCny()) / Double.valueOf(getTotalAsset())));
                            }
                        }

                    }
                    break;
                default:
                    if (new BigDecimal(getTotalAsset()).compareTo(BigDecimal.ZERO) > 0) {
                        double coinCny0 = Double.valueOf(hdwallets.get(0).getBanlanceCny());
                        double coinCny1 = Double.valueOf(hdwallets.get(1).getBanlanceCny());
                        double totalCny = Double.valueOf(getTotalAsset());

                        if (coinCny0 > 0) {
                            walletPercentList.add(new WalletPercent(hdwallets.get(0).getWalletName(), colors.get(0), coinCny0 / totalCny));
                        }
                        if (coinCny1 > 0) {
                            walletPercentList.add(new WalletPercent(hdwallets.get(1).getWalletName(), colors.get(1), coinCny1 / totalCny));
                        }

                        walletPercentList.add(new WalletPercent("其他钱包", colors.get(2), 1 - coinCny0 / totalCny - coinCny1 / totalCny));
                    }
            }
            walletPercentView.setViews(walletPercentList);
            walletPercentDetailView.setViews(walletPercentList);

        }
    }


    //----------------------------------------------event--------------------------------------------

    @Subscriber
    void onGetNewWallet(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.IS_GET_NEW_WALLET) {
            //刷新local 钱包列表 暂时只考虑eth
            getWallets();
            setVisibleView();
            flList.setVisibility(View.VISIBLE);
            llGuide.setVisibility(View.GONE);
            //连接以太坊 ，请求数据
            getLocalWalletData(true);
        }
    }


    @Subscriber
    void setAssetVisible(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.IS_ASSET_VISIBLE) {
            isVisible = (boolean) event.getData();
            setVisibleView();
        }
    }


}
